import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_core_widget/config/kq_core_global.dart';
import 'package:kq_flutter_core_widget/widgets/imageBox/kq_image_box.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';
import 'package:kq_flutter_widgets/resources/l10n/kq_intl.dart';
import 'package:kq_flutter_widgets/widgets/button/kq_select_button.dart';
import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_theme_colors.dart';
import '../dialog/kq_file_picker.dart';
import '../divider/kq_divider.dart';
import '../formItem/entity/kq_form_entity.dart';
import '../imageBox/kq_head_image_box.dart';

class KqHeadImageBoxItemView extends StatefulWidget {
  /// 数据实体类
  final KqFormEntity entity;

  ///模认图片
  final String? defaultPic;

  /// 图片添加按钮点击回调
  final Function(KqFormEntity entity, KqHeadImageBoxItemViewState state,
      VoidCallback callBack)? onAddTap;

  const KqHeadImageBoxItemView(
      {Key? key, required this.entity, this.defaultPic, this.onAddTap})
      : super(key: key);

  @override
  KqHeadImageBoxItemViewState createState() => KqHeadImageBoxItemViewState();
}

class KqHeadImageBoxItemViewState extends State<KqHeadImageBoxItemView> {
  final icoHeight = 200.r;
  int currentIndex = 0;
  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 图片数量
  int count() {
    if (widget.entity.imageUrls != null) {
      return widget.entity.imageUrls!.length;
    }
    return 0;
  }

  /// 添加图片
  void addImage(ImageUrl imageUrl) {
    int max = widget.entity.maxQty?.toInt() ?? 8;
    if ((widget.entity.imageUrls != null &&
            widget.entity.imageUrls!.length >= max) ||
        widget.entity.imageUrls == null) {
      return;
    }
    widget.entity.imageUrls!.add(imageUrl);
    setState(() {});
  }

  /// 删除按钮
  Widget _buildDeleteButton() {
    return KqImage.assets(
      url: Images.commonIcShanchuJiaobiao,
      fit: BoxFit.fill,
      width: 32.r,
      height: 32.r,
      package: KqCoreGlobal.packageName,
    );
  }

//上传图片
  Widget _buildPictures() {
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgWhite;
    return Column(
      children: [
        Container(
            color: const Color(0xffF4F4F5),
            width: context.width,
            height: icoHeight,
            alignment: Alignment.center,
            child: Stack(
              children: [
                if (widget.entity.imageUrls!.length > currentIndex)
                  KqImage.custom(
                    imageType: widget.entity.imageUrls![currentIndex].imageType,
                    width: context.width,
                    height: icoHeight,
                    url: widget.entity.imageUrls![currentIndex].url,
                    placeHolder:
                        widget.entity.imageUrls![currentIndex].placeHolder,
                    errorImage:
                        widget.entity.imageUrls![currentIndex].placeHolder,
                    fit: BoxFit.fitHeight,
                    package: widget.entity.imageUrls![currentIndex].package,
                  ),
                Visibility(
                    visible: widget.entity.editable &&
                        currentIndex == 0 &&
                        widget.entity.imageUrls!.length > 1,
                    child: Positioned(
                        left: 0,
                        top: 0,
                        child: KqSelectButton(
                          text: KqIntl.currentResource.themeHint,
                          backgroundColor: KqThemeColors.textGreen,
                          textColor: KqThemeColors.bgWhite,
                          fontSize: 12.sp,
                          padding: EdgeInsets.symmetric(
                              horizontal: 10.r, vertical: 4.r),
                        ))),
                Visibility(
                    visible: widget.entity.editable,
                    child: Positioned(
                        right: 0,
                        top: 0,
                        width: 32.r,
                        height: 32.r,
                        child: KqInkWell(
                          onTap: () {
                            if (widget.entity.imageUrls!.length >
                                currentIndex) {
                              widget.entity.imageUrls!.remove(
                                  widget.entity.imageUrls![currentIndex]);
                            }
                            if (currentIndex > 0) {
                              currentIndex--;
                            }
                            setState(() {});
                          },
                          child: _buildDeleteButton(),
                        ))),
                Visibility(
                    visible:
                        widget.entity.imageUrls != null && currentIndex > 0,
                    child: Positioned(
                        right: 16.r,
                        bottom: 12.r,
                        child: KqSelectButton(
                          text: KqIntl.currentResource.setThemeHint,
                          backgroundColor: KqThemeColors.bgBlack50,
                          textColor: KqThemeColors.bgWhite,
                          fontSize: 12.sp,
                          padding: EdgeInsets.symmetric(
                              horizontal: 6.r, vertical: 4.r),
                          radius: 2.r,
                          onTap: () {
                            //把当前的换成0位置
                            if (widget.entity.imageUrls != null &&
                                widget.entity.imageUrls!.length >
                                    currentIndex) {
                              var current =
                                  widget.entity.imageUrls![currentIndex];
                              widget.entity.imageUrls!.removeAt(currentIndex);
                              widget.entity.imageUrls!.insert(0, current);
                              setState(() {
                                currentIndex = 0;
                              });
                            }
                          },
                        ))),
              ],
            )),

        /// 图片容器
        widget.entity.imageUrls == null ||
                (widget.entity.imageUrls!.isEmpty &&
                    !widget.entity.isEditable())
            ? Container()
            : Container(
                color: bgColor,
                padding: EdgeInsets.only(
                    left: 16.r, right: 16.r, top: 16.r, bottom: 16.r),
                child: KqHeadImageBox(
                  urls: widget.entity.imageUrls!,
                  maxQty: widget.entity.maxQty?.toInt() ?? 8,
                  cols: widget.entity.imageBoxCols,
                  chooseIndex: currentIndex,
                  customAddPic: Images.commonPicUpload88Grey,
                  onAddTap: (urls, state) {
                    //默认点击添加按钮实现
                    if (widget.onAddTap == null) {
                      KqFilePicker(
                              maxCount: (widget.entity.maxQty?.toInt() ?? 8) -
                                  state.count())
                          .choosePhoto(
                        context,
                        (files) {
                          for (var file in files) {
                            state.addImage(ImageUrl(
                                imageType: ImageType.file,
                                url: file.filePath!));
                          }
                          setState(() {
                            currentIndex = state.count() - 1;
                          });
                        },
                      );
                      return;
                    }
                    if (widget.onAddTap != null) {
                      widget.onAddTap!.call(widget.entity, this, () {
                        setState(() {
                          currentIndex = state.count() - 1;
                        });
                      });
                    }
                  },
                  onImageTap: (urls, imageUrl, position, state) {
                    setState(() {
                      currentIndex = position;
                    });
                  },
                  onChanged: () {
                    setState(() {});
                  },
                  editable: widget.entity.isEditable(),
                ),
              ),

        /// 分割线
        Visibility(
            visible: !widget.entity.hideDivider, child: const KqDivider())
      ],
    );
  }

  //未上传图片
  Widget _buildNoPictures() {
    return KqInkWell(
        onTap: () {
          //默认点击添加按钮实现
          if (widget.onAddTap == null) {
            int max = widget.entity.maxQty?.toInt() ?? 8;
            KqFilePicker(maxCount: max).choosePhoto(
              context,
              (files) {
                for (var file in files) {
                  addImage(
                      ImageUrl(imageType: ImageType.file, url: file.filePath!));
                }
                setState(() {});
              },
            );
            return;
          }
          if (widget.onAddTap != null) {
            widget.onAddTap!(widget.entity, this, (() {
              setState(() {
                currentIndex = this.count() - 1;
              });
            }));
          }
        },
        child: Container(
          color: const Color(0xffF4F4F5),
          width: context.width,
          height: icoHeight,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              KqImage.assets(
                url: widget.defaultPic ?? Images.commonPicUpload88,
                width: 100.r,
                height: 100.r,
                fit: BoxFit.fitWidth,
                package: widget.defaultPic != null && widget.defaultPic != ''
                    ? null
                    : KqGlobal.packageName,
              ),
              Text(
                KqIntl.currentResource.uploadImageHint,
                style: TextStyle(color: KqThemeColors.text59, fontSize: 14.sp),
              )
            ],
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    return Visibility(
      visible: widget.entity.visible,
      child:
          widget.entity.imageUrls != null && widget.entity.imageUrls!.isNotEmpty
              ? _buildPictures()
              : _buildNoPictures(),
    );
  }
}
